let _ = require('lodash');
let config = require('../config');
let classModel = require('../models/class.model');

module.exports = {

    /**
     * 获取所有分类
     * @param req
     * @param res
     * @param next
     */
    adminClasses(req, res, next) {
        classModel.findAll().then(cs => {
            res.jsonSuccess(cs);
        }).catch(e => {
            res.jsonFail(e.message);
        });
    },

    /**
     * 获取可见分类
     * @param req
     * @param res
     * @param next
     */
    classes(req, res, next) {
        classModel.findAll({attributes: ['id', 'name'], where: {visible: true}}).then(cs => {
            res.jsonSuccess(cs);
        }).catch(e => {
            res.jsonFail(e.message);
        });
    },

    /**
     * 更新分类信息
     * @param req
     * @param res
     * @param next
     */
    update(req, res, next) {
        let id = req.body.id;
        let name = req.body.name;
        let leaf = req.body.leaf;
        let visible = req.body.visible;

        if (_.isNil(id)) {
            res.jsonFail('分类ID不能为空！');
            return;
        }

        if (_.isNil(name) || _.isEmpty(name)) {
            res.jsonFail('分类名不能为空！');
            return;
        }

        if (_.isNil(visible) || !_.isBoolean(visible)) {
            res.jsonFail('显示状态不能为空！');
            return;
        }

        if (_.isNil(leaf)) {
            leaf = [];
        }
        classModel.findOne({attributes: ['id'], where: {id: id}}).then(cls => {
            if (!cls) {
                res.jsonFail('分类不存在！');
                return;
            }
            cls.name = name;
            cls.leaf = leaf;
            cls.visible = visible;
            return cls.save().then(c => {
                res.jsonSuccess();
            }).catch(e => {
                res.jsonFail(e.message);
            });
        }).catch(e => {
            res.jsonFail('系统错误！');
        });
    },

    /**
     * 增加分类
     * @param req
     * @param res
     * @param next
     */
    add(req, res, next) {
        let name = req.body.name;
        let leaf = req.body.leaf;
        let visible = req.body.visible;
        if (_.isNil(name) || _.isEmpty(name)) {
            res.jsonFail('分类名不能为空！');
            return;
        }
        if (_.isNil(visible) || !_.isBoolean(visible)) {
            res.jsonFail('显示状态不能为空！');
            return;
        }
        if (_.isNil(leaf)) {
            leaf = [];
        }
        classModel.create({name: name, leaf: leaf, visible: visible}).then(cls => {
            res.jsonSuccess(cls);
        }).catch(e => {
            res.jsonFail('系统错误！');
        });
    },
};
